package com.echo.util;

import com.google.gson.*;

import java.util.ArrayList;
import java.util.List;

public class GsonTools {

	private static Gson defaultGson = defaultGson();

	private static Gson instanceGson = instanceGson();

	private static Gson instanceGson() {
		GsonBuilder builder = new GsonBuilder();
		builder.serializeNulls();
		builder.registerTypeAdapter(String.class, new StringTypeAdapter());
		return builder.create();
	}

	private static Gson defaultGson() {
		GsonBuilder builder = new GsonBuilder();
		builder.serializeNulls();
		Gson gson = builder.create();
		return gson;
	}

	public static String inst2JSON(Object inst) {
		return instanceGson.toJson(inst);
	}

	public static String element2JSON(JsonElement jsonElement) {

		return instanceGson.toJson(jsonElement);
	}

	public static <T> T json2Inst(String json, Class<T> clazz) {
		return instanceGson.fromJson(json, clazz);
	}

	public static String object2String(Object value) {
		String jsonString = defaultGson.toJson(value);
		return jsonString;
	}

	public static <T> T string2Object(String json, Class<T> clazz) {
		return defaultGson.fromJson(json, clazz);
	}

	public static String getMemberValue(String json, String memberName) {
		JsonParser parser = new JsonParser();
		JsonElement element = parser.parse(json);
		JsonObject objcet = element.getAsJsonObject();
		if (objcet.has(memberName)) {
			JsonElement memberElement = objcet.get(memberName);
			if (memberElement.isJsonObject()) {
				return memberElement.toString();
			} else if (memberElement.isJsonPrimitive()) {
				return memberElement.getAsString();
			} else if (memberElement.isJsonArray()) {
				return memberElement.toString();
			} else if (memberElement.isJsonNull()) {
				return null;
			} else {
				return null;
			}
		} else {
			return null;
		}
	}

	public static List<Object> getJsonList(String json, Class<? extends Object> clazz) {
		List<Object> resultList = new ArrayList<Object>();
		JsonParser parser = new JsonParser();
		JsonElement element = parser.parse(json);
		JsonArray jsonArray = element.getAsJsonArray();
		for (JsonElement jsonElement : jsonArray) {
			resultList.add(element2Object(jsonElement, clazz));
		}
		return resultList;
	}

	public static Object element2Object(JsonElement element, Class<? extends Object> clazz) {
		Object value = defaultGson.fromJson(element, clazz);
		return value;
	}
}
